package com.example.classes;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;


/**
 * This class represents the database structure used to store the users objects
 * @author Ankit Pasi
 * @version 1.0
 */

public class DataBase{

    MyDBHelper help;
    public static final String DATABASE_NAME="USERLIST";
    public static final String TABLE_USER="user";
    public static final String COLUMN_USER = "user";
    public static final String COLUMN_PASS="password";
    public static final String COLUMN_CONTACT="contact";
    public static final String COLUMN_LOCKED="locked";
    public static final String COLUMN_ITEMS="items";
    public static final String DATABASE_CREATE="create table "+TABLE_USER+"("+COLUMN_USER+" text not null primary key, "+COLUMN_PASS+" text not null, " +
    COLUMN_CONTACT+" text not null, "+ COLUMN_ITEMS+" text not null, "+ COLUMN_LOCKED+" text"+" );";

    private SQLiteDatabase data;
    private Context c;
                   private Gson gson;

    public DataBase(Context context)
    {
        help=new MyDBHelper(context);
        c=context;
        gson=new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
    }
    /**
     * Getter for database data
     * @return           the database object
     */
    public SQLiteDatabase getData() {
        return data;
    }


    public void open()
    {
        try{
        data=help.getWritableDatabase();
        }
        catch(Exception e){Toast.makeText(c,"Exception while opening database: "+e.getMessage(),Toast.LENGTH_LONG).show();}
    }

    /**
     * Adds a user to the database
     * @param s   the user
     */
    public void createUserEntry(Member s)
    {

        try{
            this.open();
            String itemList= gson.toJson(s.getItems());
            ContentValues val= new ContentValues();
            val.put(COLUMN_USER,s.getName());
            val.put(COLUMN_PASS,s.getPassword());
            val.put(COLUMN_ITEMS,itemList);
            val.put(COLUMN_LOCKED,s.isLocked());
            val.put(COLUMN_CONTACT,s.getContact());
            data.insert(TABLE_USER,null,val);
            data.close();
        } catch(Exception e)
        {
            Toast.makeText(c, "ERROR: "+e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }

    /**
     *          Function to delete entry from database
     * @param uname
     */
    public void deleteUserEntry(String uname)
    {
        data.delete(TABLE_USER,COLUMN_USER+" = "+uname,null);
    }
    public Member getEntry(String uname)
    {
        Cursor curse;
        this.open();
        String query= "SELECT * FROM "+TABLE_USER+" WHERE "+COLUMN_USER+" = '"+uname+"'";
        this.open();
        if(data!=null)
        {
            curse=data.rawQuery(query,null);
            if (curse.moveToFirst())
            {
                ArrayList<Item> items= new ArrayList<Item>();
                gson=new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                String userid=curse.getString(0);
                String userpass=curse.getString(1);
                String itemList=curse.getString(3);
                String contact=curse.getString(2);
                boolean locked=Boolean.parseBoolean(curse.getString(4));
                Type type = new TypeToken<ArrayList<Item>>(){}.getType();
                try{
                    items = gson.fromJson(itemList, type);
                }
                catch(Exception ex){
                    Toast.makeText(null,"Exception "+ex.getMessage(),Toast.LENGTH_LONG).show();
                }
                curse.close();
                User res=new User(userid,userpass,contact,locked);
                res.setItems(items);
                return res;
            }
        }
        return null;
    }
    public Collection<Member> getAllUsers()
    {
        this.open();
        Log.v("Database","******  getAllUsers");
        ArrayList<Member> memberList= new ArrayList<Member>();
        Cursor curse;
        String query="SELECT * FROM "+ TABLE_USER;
        curse=data.rawQuery(query,null);
        Log.v("Database","******  ONE");
        curse.moveToFirst();
        while(curse.isAfterLast()==false)
        {
            memberList.add(cursorToUser(curse));
            curse.moveToNext();
        }
        Log.v("Database","******  TWO");
        curse.close();
        return memberList;
    }
    private Member cursorToUser(Cursor curse)
    {
        Type type = new TypeToken<ArrayList<Item>>(){}.getType();
        gson= new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        ArrayList<Item> items= new ArrayList<Item>();
        String userid=curse.getString(0);
        String userpass=curse.getString(1);
        String itemList=curse.getString(3);
        String contact=curse.getString(2);
        boolean locked=Boolean.parseBoolean(curse.getString(4));
        try{
            items = gson.fromJson(itemList, type);
        }
        catch(Exception ex){
           // Toast.makeText(null,"Exception "+ex.getMessage(),Toast.LENGTH_LONG).show();
        }
        User res= new User(userid,userpass,contact,locked);
        res.setItems(items);
        return res;
    }
    public void update(Member m)
    {
        String filter= COLUMN_USER+" = '"+m.getName()+"';";
        String items= gson.toJson(m.getItems());
        ContentValues args= new ContentValues();
        args.put(COLUMN_ITEMS,items);
        data.update(TABLE_USER,args,filter,null);
    }
    public void del()
    {
        help.deleteDatabase();
    }
    public void close()
    {
        data.close();
    }

}
